package org.example.c2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author liu-rui
 * @date 2020/6/8 上午10:08
 * @description
 * 通过unsafe动态加载Customer
 * @since
 */
@Slf4j
public class Demo8 {
    public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        final byte[] bytes = Files.readAllBytes(Paths.get( "target/classes/org/example/c2/Customer.class"));
        final Class<?> defineClass = MyUnSafe.getUnsafe().defineClass( null, bytes, 0, bytes.length,
                null,
                null);
        //类是否需要被初始化，由于defineClass只是将类装载到方法区中并未初始化，所以此处返回true
        log.info("{}" , MyUnSafe.getUnsafe().shouldBeInitialized(defineClass));
        log.info("name: {}" , defineClass.getName());
        //执行初始化动作
        MyUnSafe.getUnsafe().ensureClassInitialized(defineClass);
        //由于已经初始化，这里返回结果为false
        log.info("{}" , MyUnSafe.getUnsafe().shouldBeInitialized(defineClass));

        //实例化
        final Constructor<?> constructor = defineClass.getConstructor(String.class, String.class);
        final Object instance = constructor.newInstance("1", "张三");
        log.info("输出实例{}" , instance.toString());
    }
}
